package thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-09-25
 * Time: 17:47
 */
class MyQueue{
    Object locker = new Object();
    String[] elems = null;
    int head = 0;//记录出元素时
    int tail = 0;//记录进元素时
    int size = 0;//当前队列中有多少个元素
    public MyQueue(int capacity){
        elems = new String[capacity];
    }
    public void put(String elem) throws InterruptedException {
        synchronized(locker){
            while (size >= elems.length ){
                locker.wait();//满了等待，等待有元素出队列就唤醒
            }
            elems[tail] = elem;
            tail++;
            if(tail >= elems.length){
                tail = 0;
            }
            size++;
            locker.notify();
        }

    }
    public String take() throws InterruptedException {
        String elem = null;
        synchronized (locker){
            while(size <= 0){
                locker.wait();
            }
            elem = elems[head];
            head++;
            if (head >= elems.length){
                head = 0;
            }
            size--;
            locker.notify();//有元素出了，唤醒put方法
        }

        return elem;
    }

}
public class ThreadDemon31 {
    public static void main(String[] args) throws InterruptedException {
        MyQueue queue = new MyQueue(100);
        Thread t1 = new Thread(()->{
            int n = 0;
            while(true){
                try {
                    queue.put(n + " ");
                    System.out.println("生产元素："  + n);
                    n++;
                  /*  Thread.sleep(1000);*/
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });


        Thread t2 = new Thread(()->{
           while(true){
               try {
                   System.out.println("消费元素：" + queue.take());
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });
        t1.start();
        t2.start();
        /*
        queue.put("aaa");
        queue.put("bbb");
        queue.put("ccc");
        queue.put("ddd");
        System.out.println("开始出队列");
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
        */
    }
}
